using System;
using ch.ethz.ssh2;
using ch.ethz.ssh2.util;
namespace ch.ethz.ssh2.transport
{
	
	/// <summary> ClientServerHello.
	/// 
	/// </summary>
	/// <author>  Christian Plattner
	/// </author>
	/// <version>  2.50, 03/15/10
	/// </version>
	public class ClientServerHello
	{
		/// <returns> Returns the client_versioncomment.
		/// </returns>
		virtual public byte[] ClientString
		{
			get
			{
				return StringEncoder.GetBytes(client_line);
			}
			
		}
		/// <returns> Returns the server_versioncomment.
		/// </returns>
		virtual public byte[] ServerString
		{
			get
			{
				return StringEncoder.GetBytes(server_line);
			}
			
		}
		internal System.String server_line;
		internal System.String client_line;
		
		internal System.String server_versioncomment;
		
		public static int readLineRN(System.IO.Stream input, byte[] buffer)
		{
			int pos = 0;
			bool need10 = false;
			int len = 0;
			while (true)
			{
				int c = input.ReadByte();
				if (c == - 1)
					throw new System.IO.IOException("Premature connection close");
				
				buffer[pos++] = (byte) c;
				
				if (c == 13)
				{
					need10 = true;
					continue;
				}
				
				if (c == 10)
					break;
				
				if (need10 == true)
					throw new System.IO.IOException("Malformed line sent by the server, the line does not end correctly.");
				
				len++;
				if (pos >= buffer.Length)
					throw new System.IO.IOException("The server sent a too long line.");
			}
			
			return len;
		}
		
		public ClientServerHello(System.IO.Stream bi, System.IO.Stream bo)
		{
			client_line = "SSH-2.0-" + Connection.identification;
			
			if (bo is ch.ethz.ssh2.channel.ChannelOutputStream)
				((ch.ethz.ssh2.channel.ChannelOutputStream) bo).write(StringEncoder.GetBytes(client_line + "\r\n"));
			else
			{
				byte[] temp_byteArray;
				temp_byteArray = StringEncoder.GetBytes(client_line + "\r\n");
				bo.Write(temp_byteArray, 0, temp_byteArray.Length);
			}
			bo.Flush();
			
			byte[] serverVersion = new byte[512];
			
			for (int i = 0; i < 50; i++)
			{
				int len = readLineRN(bi, serverVersion);
				
				server_line = StringEncoder.GetString(serverVersion, 0, len);
				
				if (server_line.StartsWith("SSH-"))
					break;
			}
			
			if (server_line.StartsWith("SSH-") == false)
				throw new System.IO.IOException("Malformed server identification string. There was no line starting with 'SSH-' amongst the first 50 lines.");
			
			if (server_line.StartsWith("SSH-1.99-"))
				server_versioncomment = server_line.Substring(9);
			else if (server_line.StartsWith("SSH-2.0-"))
				server_versioncomment = server_line.Substring(8);
			else
				throw new System.IO.IOException("Server uses incompatible protocol, it is not SSH-2 compatible.");
		}
	}
}